<template>
    <div class="app-container">
      <el-row :gutter="20">
        <!--用户数据-->
        <el-col :span="24" :xs="24">
          <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="场馆名称" prop="userName">
              <el-input
                v-model="queryParams.venueName"
                placeholder="请输入场馆名称"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="场馆号码" prop="phone">
              <el-input
                v-model="queryParams.venuePhone"
                placeholder="请输入场馆手机号码"
                clearable
                style="width: 240px"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="创建时间">
              <el-date-picker
                v-model="dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
  
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                >新增</el-button
              >
            </el-col>
            <right-toolbar
              :showSearch.sync="showSearch"
              @queryTable="getList"
              :columns="columns"
            ></right-toolbar>
          </el-row>
  
          <el-table v-loading="loading" :data="userList">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              label="食谱名称"
              align="center"
              width="320"
              key="recipeName"
              prop="recipeName"
              v-if="columns[1].visible"
              :show-overflow-tooltip="true"
            />
            <el-table-column  
            label="食谱封面" 
            align="center" 
            width="320"
            v-if="columns[3].visible" 
            key="recipeFileId"
            prop="recipeFileId">
              <template slot-scope="scope">
                <el-image style="width: 60px; height: 60px" :src="'http://101.43.223.224:8765/image/getImageById?id=' + scope.row.recipeFileId"></el-image>
                </template>
            </el-table-column>
            <el-table-column
              label="创建时间"
              align="center"
              prop="createTime"
              v-if="columns[6].visible"
              width="320"
            >
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              align="center"
              width="450"
              class-name="small-padding fixed-width"
            >
              <template slot-scope="scope" v-if="scope.row.userId !== 1">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="handleUpdate(scope.row)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
  
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
  
      <!-- 添加场馆配置对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="食谱封面">
                <el-upload
                  class="avatar-uploader"
                  action=""
                  list-type="picture-card"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                >
                  <el-image
                    style="width: 145px; height: 146px"
                    v-if="carouselImg"
                    :src="carouselImg"
                    class="avatar"
                  ></el-image>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="食谱名称" prop="recipeName">
                <el-input
                  v-model="form.recipeName"
                  placeholder="请输入食谱名称"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm('form')">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
  
      <!-- 修改场馆配置对话框 -->
      <el-dialog :title="title" :visible.sync="upopen" width="600px" append-to-body>
        <el-form ref="updateform" :model="updateform" :rules="rules" label-width="120px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="食谱封面">
                <el-upload
                  class="avatar-uploader"
                  action=""
                  list-type="picture-card"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUploadup"
                >
                  <el-image
                    style="width: 145px; height: 146px"
                    v-if="carouselupImg"
                    :src="carouselupImg"
                    class="avatar"
                  ></el-image>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="食谱名称" prop="recipeName">
                <el-input
                  v-model="updateform.recipeName"
                  placeholder="请输入食谱名称"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitupdateform('updateform')">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { addVenue,listRecipe,updateVenue,delUser,changeUserStatus } from "@/api/recipe/recipe";
  import { getToken } from "@/utils/auth";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  let pcas = require("@/pcas/pcas-code.json")
  export default {
    name: "User",
    dicts: ["sys_normal_disable", "sys_user_sex"],
    components: { Treeselect },
  
    data() {
      return {
        options: pcas, // 从pcas-code.json文件中读取的原始数据
        selectedOptions: [],// 多级地理位置下拉菜单
        carouselImg: "", //添加图片路径及其图片
        imgCarousel: "", //添加图片信息
        carouselupImg:'',//修改图片路径及其图片
        imgupCarousel:'',//修改图片信息
        // 是否显示修改弹出框
        upopen: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户表格数据
        userList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 日期范围
        dateRange: [],
        // 岗位选项
        postOptions: [],
        // 表单参数
        form: {},
        updateform: {},
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          venueName: undefined,
          venuePhone: undefined,
        },
        // 列信息
        columns: [
          { key: 0, label: `场馆编号`, visible: true },
          { key: 1, label: `场馆名称`, visible: true },
          { key: 2, label: `场馆手机号`, visible: true },
          { key: 3, label: `场馆证书`, visible: true },
          { key: 4, label: `场馆位置`, visible: true },
          { key: 5, label: `场馆负责人姓名`, visible: true },
          { key: 6, label: `创建时间`, visible: true },
        ],
        // 表单校验
        rules: {
          venueDirectorIdcard: [
            { required: true, message: "请输入身份证号", trigger: "blur" },
            {
              //调用定义的方法校验格式是否正确
              validator: this.validateIdNo,
              trigger: "blur",
            },
          ],
          venueName: [
            { required: true, message: "场馆名称不能为空", trigger: "blur" },
          ],
          venueHeadName: [
            { required: true, message: "负责人姓名不能为空", trigger: "blur" },
          ],
          venuePhone: [
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur",
            },
          ],
        },
      };
    },
    computed: {
      transformOptions() {
        return this.options.map(province => ({
          value: province.name,
          label: province.name,
          children: province.children.map(city => ({
            value: city.name,
            label: city.name,
            children: city.children.map(county => ({
              value: county.name,
              label: county.name,
              children: county.children.map(town => ({
                value: town.name,
                label: town.name
              }))
            }))
          }))
        }));
      }
    },
    created() {
      this.getList();
    },
    methods: {
      /** 查询用户列表 */
      getList() {
        console.log();
        this.loading = true;
        listRecipe(this.addDateRange(this.queryParams, this.dateRange)).then(
          (res) => {
            this.userList = res.data.content;
            this.total = res.data.totalSize;
            this.loading = false;
          }
        );
      },
      // 筛选节点
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 节点单击事件
      handleNodeClick(data) {
        this.queryParams.deptId = data.id;
        this.handleQuery();
      },
      // // 用户状态修改
      // handleStatusChange(row) {
      //   console.log(row);
      //   let text = row.delFlag === "0" ? "启用" : "停用";
      //   this.$modal
      //     .confirm('确认要"' + text + '""' + row.venueName + '"场馆吗？')
      //     .then(function () {
      //       return changeUserStatus(row.id, row.delFlag);
      //     })
      //     .then(() => {
      //       this.$modal.msgSuccess(text + "成功");
      //     })
      //     .catch(function () {
      //       row.delFlag = row.delFlag === "0" ? "1" : "0";
      //     });
      // },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.carouselImg = '';
        this.resetForm("form");
      },
      // 删除按钮操作
      handleDelete(row) {
      // const userIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户编号为"' + id + '"的数据项？').then(function() {
        return delUser(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.$refs.tree.setCurrentKey(null);
        this.handleQuery();
      },
      // 文件上传校验
      beforeAvatarUpload(file) {
        //上传图片格式
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG && !isPNG) {
          this.$message.error("上传图片只能是JPG/PNG格式!");
          return false;
        }
        if (!isLt2M) {
          this.$message.error("上传图片大小不能超过2MB!");
          return false;
        }
        this.imgCarousel = file;
        this.carouselImg = URL.createObjectURL(file);
        return false;
      },
      beforeAvatarUploadup(file) {
        //上传图片格式
        const isJPG = file.type === "image/jpeg";
        const isPNG = file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG && !isPNG) {
          this.$message.error("上传图片只能是JPG/PNG格式!");
          return false;
        }
        if (!isLt2M) {
          this.$message.error("上传图片大小不能超过2MB!");
          return false;
        }
        this.imgupCarousel = file;
        this.carouselupImg = URL.createObjectURL(file);
        return false;
      },
      /** 新增按钮操作 */
      handleAdd() {
        // 重置表单
        this.reset();
        this.open = true;
        this.title = "添加场馆信息";
      },
      // 添加场馆操作
      submitForm(form) {
        if(this.imgCarousel == ''||this.imgCarousel == undefined){
          return this.$message.error("图片不能为空");
        }
        this.$refs[form].validate((valid) => {
          if (valid) {
            const formData = new FormData();
            formData.set("recipeName", this.form.recipeName);
            // 轮播图片
            if (this.imgCarousel) {
              formData.set("file", this.imgCarousel, this.imgCarousel.name);
            }
            addVenue(formData)
              .then((res) => {
                if (res.data) {
                  this.$message.success(res.data.data);
                  this.getList()
                  this.open = false
                } else {
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            this.$message.error("请按照要求输入信息");
            console.log("error submit!!");
            return false;
          }
        });
      },
      // 修改按钮
      handleUpdate(row) {
        this.carouselupImg = 'http://101.43.223.224:8765/image/getImageById?id=' + row.recipeFileId;
        this.updateform = JSON.parse(JSON.stringify(row))
        this.upopen = true;
        this.title = "修改场馆信息";
      },
      // 修改方法
      submitupdateform(updateform){
        console.log(this.updateform.id);
        this.$refs[updateform].validate((valid) => {
          if (valid) {
            const formData = new FormData();
            formData.set("id", this.updateform.id);
            formData.set("recipeFileId", this.updateform.recipeFileId);
            formData.set("recipeName", this.updateform.recipeName);
            // 轮播图片
            if (this.imgupCarousel) {
              formData.set("file", this.imgupCarousel, this.imgupCarousel.name);
            }
            updateVenue(formData)
              .then((res) => {
                if (res.data) {
                  this.$message.success(res.data.data);
                  this.getList()
                  this.upopen = false
                } else {
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else {
            this.$message.error("请按照要求输入信息");
            console.log("error submit!!");
            return false;
          }
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download(
          "system/user/export",
          {
            ...this.queryParams,
          },
          `user_${new Date().getTime()}.xlsx`
        );
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "用户导入";
        this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download(
          "system/user/importTemplate",
          {},
          `user_template_${new Date().getTime()}.xlsx`
        );
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
            response.msg +
            "</div>",
          "导入结果",
          { dangerouslyUseHTMLString: true }
        );
        this.getList();
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      handleChange(value){
        console.log(value)
      },
        // 身份证号码校验 
      validateIdNo(rule, value, callback) {
          if (!value) {
            return callback(new Error("身份证号码不能为空"));
          }
          function validataCredentials(num) {
            var msg, boo; //  msg身份证验证友情提示,boo返回值
            var num = num.toUpperCase(); // 身份证为末尾可能是X
            //   身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，
            //   最后一位是校验位，可能为数字或字符X。
            const arrInt = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
            const arrCh = new Array("1","0","X","9","8","7","6","5","4","3","2");
            var nTemp = 0,
              i;
            if (!/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num)) {
              //  输入的身份证号长度不对，或者号码不符合规定;
              return [(boo = false), (msg = "身份证号长度不对，或号码不符")];
            }
            //   校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
            //   下面分别分析出生日期和校验位
            var len, re;
            len = num.length;
            if (len == 15) {
              re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
              var arrSplit = num.match(re);
              //   检查生日日期是否正确
              var dtmBirth = new Date(
                "19" + arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]
              );
              var bGoodDay;
              bGoodDay =
                dtmBirth.getYear() == Number(arrSplit[2]) &&
                dtmBirth.getMonth() + 1 == Number(arrSplit[3]) &&
                dtmBirth.getDate() == Number(arrSplit[4]);
              if (!bGoodDay) {
                //   输入的身份证号里出生日期不对！
                return [(boo = false), (msg = "输入的身份证号里出生日期不对！")];
              } else {
                //   将15位身份证转成18位
                //   校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                num = num.substr(0, 6) + "19" + num.substr(6, num.length - 6);
                for (i = 0; i < 17; i++) {
                  nTemp += num.substr(i, 1) * arrInt[i];
                }
                num += arrCh[nTemp % 11];
                return [(boo = true), (msg = num)];
              }
            }
            if (len == 18) {
              re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
              var arrSplit = num.match(re);
              //  检查生日日期是否正确
              var dtmBirth = new Date(
                arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]
              );
              var bGoodDay;
              bGoodDay =
                dtmBirth.getFullYear() == Number(arrSplit[2]) &&
                dtmBirth.getMonth() + 1 == Number(arrSplit[3]) &&
                dtmBirth.getDate() == Number(arrSplit[4]);
              if (!bGoodDay) {
                //  输入的身份证号里出生日期不对！
        
                return [(boo = false), (msg = " 输入的身份证号里出生日期不对")];
              } else {
                //  检验18位身份证的校验码是否正确。
                //  校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                var valnum;
                for (i = 0; i < 17; i++) {
                  nTemp += num.substr(i, 1) * arrInt[i];
                }
                valnum = arrCh[nTemp % 11];
                if (valnum != num.substr(17, 1)) {
                  //  18位身份证的校验码不正确！
                  return [(boo = false), (msg = "身份证的校验码不正确！")];
                }
                return [(boo = true), (msg = "验证成功")];
              }
            }
            return [(boo = false), (msg = "身份证的长度不正确！")];
          }
          setTimeout(() => {
            var res = validataCredentials(value);
            if (!res[0]) {
              callback(new Error(res[1]));
            } else {
              callback();
            }
          }, 200);
      }
    },
  };
  </script>